package cn.demo.rocketmq.transaction.demo1;


import cn.demo.rocketmq.transaction.demo1.util.FastJsonUtil;
import cn.demo.rocketmq.transaction.demo1.util.Order;
import cn.demo.rocketmq.transaction.demo1.util.OrderMapper;
import org.apache.rocketmq.client.producer.LocalTransactionExecuter;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;


/**
 * 处理本地业务逻辑
 */
@Component
public class TransactionExecuterImpl implements LocalTransactionExecuter {

    @Autowired
    private OrderMapper orderMapper;

    @Override
//    @Transactional
    public LocalTransactionState executeLocalTransactionBranch(final Message msg, final Object arg) {

        try {

            System.out.println("本地逻辑执行了。。。");
            //Message Body
            Order order = FastJsonUtil.jsonToBean(new String(msg.getBody(), "utf-8"), Order.class);

            order.setState(Order.COMPLETED);
            //将之前的订单 根据用户id和订单号 修改为已确认发送状态
            this.orderMapper.update(order);

            //成功通知MQ消息变更 该消息变为：<确认发送>
            return LocalTransactionState.COMMIT_MESSAGE;

            //这里方便测试 自定义事务回查 所以返回 未知状态
            //return LocalTransactionState.UNKNOW;

        } catch (Exception e) {
            e.printStackTrace();
            //失败回滚
            return LocalTransactionState.ROLLBACK_MESSAGE;

        }

    }
}
